/*
 * Copyright (c) 2023, LXMS (lxinet.cn).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.lxinet.lxms.framework.security.helper;

import cn.lxinet.lxms.framework.security.entity.LxmsUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 权限工具
 *
 * @author zcx
 * @date 2023/07/21
 */
public class SecurityHelper {

    /**
     * 获取登录用户
     *
     * @return {@link LxmsUser}
     */
    public static LxmsUser getLoginUser(){
        if (getContext() == null || getContext().getAuthentication() == null){
            return null;
        }
        if (getContext().getAuthentication().getPrincipal() instanceof LxmsUser){
            return (LxmsUser) getContext().getAuthentication().getPrincipal();
        }
        return null;
    }

    public static List<String> getPermissions(){
        Collection<? extends GrantedAuthority> grantedAuthorities = getContext().getAuthentication().getAuthorities();
        List<String> permissions = new ArrayList<>();
        grantedAuthorities.forEach(a -> permissions.add(a.getAuthority()));
        return permissions;
    }

    public static SecurityContext getContext(){
        return SecurityContextHolder.getContext();
    }
}
